<template>
  <div id="clue_enroll_choose" class="container">
    <div class="title">
      <span v-if="clue.name=='续费'">续费</span>
      <span v-else>报名</span>
      （{{clue.realName}}）
      <div class="close" @click="cancel()"></div>
    </div>

    <div class="nav_div">
      <div class="nav" :class="checkTab==1? 'nav_active':''" @click="selectType(1)">报课</div>
      <div class="nav" :class="checkTab==2? 'nav_active':''" @click="selectType(2)">商品</div>
    </div>

    <div class="content" v-show="checkTab==1">
      <div class="condition">
        <div class="tip">请选择课程/班级</div>
        <el-input
          class="search"
          @input="searchCourse()"
          suffix-icon="el-icon-search"
          v-model="courseParam.courseName"
          placeholder="输入课程名称查询"
        />
      </div>

      <div class="table">
        <div class="thead">
          <div style="width: 0.4rem;"></div>
          <div style="width: 1.9rem;">名称</div>
          <div style="width: 1rem;">授课模式</div>
          <div style="width: 1.1rem;">收费模式</div>
          <!--<div style="width: 0.8rem;">数量</div>
          <div style="width: 0.6rem;">单位</div>-->
          <div style="width: 1.2rem;">课程时间</div>
          <div style="width: 1.5rem;">首次上课时间</div>
          <div style="width: 1rem;">班级进度</div>
          <div style="width: 1rem;">教师</div>
          <div style="width: 1rem;">班级学员</div>
          <div style="width: 1rem;">班级状态</div>
        </div>
        <div class="tbody">
          <div class="tr_div" v-for="item in courseList">
            <div class="tr">
              <div class="tr_icon" @click="showSub($event)"></div>

              <div style="width: 1.9rem;" v-if="item.classId" class="tr_two_row">
                <div>{{item.classId?item.className : ''}}</div>
                <div>{{item.courseName}}</div>
              </div>
              <div style="width: 1.9rem;" v-else>{{item.courseName}}</div>

              <div style="width: 1rem;">{{courseModeMap[item.courseMode]}}</div>
              <div style="width: 1.1rem;">{{chargeModeMap[item.chargeMode]}}</div>

              <!--<div style="width: 0.8rem;">
								{{item.classId? item.totalHour : ''}}
							</div>
							<div style="width: 0.6rem;">
								{{item.classId? item.unitName : ''}}
              </div>-->
              <div style="width: 1.2rem;" class="tr_two_row">
                <div>{{item.classId? item.startTime : ''}}</div>
                <div>{{item.classId? item.endTime : ''}}</div>
              </div>
              <div style="width: 1.5rem;" class="tr_two_row">
                <div>{{item.classId? item.firstDay : ''}}</div>
                <div>{{item.classId? item.firstTime : ''}}</div>
              </div>
              <div style="width: 1rem;">{{item.classId? item.useCourseHour+'/'+item.totalHour : ''}}</div>
              <div style="width: 1rem;">{{item.classId? item.teacherUserName : ''}}</div>
              <div style="width: 1rem;">{{item.classId? item.studentNum+'/'+item.recruitNum : ''}}</div>
              <div style="width: 1rem;">{{item.classId? classModeMap[item.classStatusMode] : ''}}</div>
            </div>
            <div class="sub_div" hidden>
              <div
                class="sub"
                v-for="pack in item.coursePackageEntityList"
                @click="checkCourse(item,pack)"
              >
                <div
                  class="sub_icon"
                  :class="c_checkList.indexOf(item.classId+'-'+item.courseId+'-'+pack.coursePackageId)>-1? 'sub_icon_active':''"
                ></div>
                <div class="sub_money">￥{{pack.totalMoney}}</div>
                <div class="sub_time">{{pack.courseHour}}{{getUnit(item,pack)}}</div>
              </div>
            </div>
          </div>
        </div>

        <!--<el-pagination class="page"
			      layout="total, prev, pager, next"
			      :current-page="1"
			      :total="20">
        </el-pagination>-->
      </div>
    </div>

    <div class="content" v-show="checkTab==2">
      <div class="condition">
        <div class="tip">请选择商品</div>
        <el-input
          class="search"
          @input="searchGoods()"
          suffix-icon="el-icon-search"
          v-model="goodsParam.name"
          placeholder="输入商品名称查询"
        />
      </div>

      <div class="table">
        <div class="thead">
          <div style="width: 0.8rem;"></div>
          <div style="width: 3rem;">名称</div>
          <div style="width: 2.2rem;">分类</div>
          <div style="width: 2.2rem;">单价</div>
          <div style="width: 2.2rem;">库存</div>
        </div>
        <div class="tbody">
          <div class="tr_div" v-for="item in goodsList">
            <div class="tr">
              <div
                style="width: 0.8rem;margin-left: 0;background-position: center;"
                class="sub_icon"
                @click="checkGoods(item)"
                :class="g_checkList.indexOf(item.goodsId)>-1? 'sub_icon_active':''"
              ></div>
              <div style="width: 3rem;">{{item.name}}</div>
              <div style="width: 2.2rem;">{{goodsModeMap[item.goodsMode]}}</div>
              <div style="width: 2.2rem;">￥{{item.salesPrice}}</div>
              <div style="width: 2.2rem;">{{item.stockNum}}件</div>
            </div>
          </div>
        </div>

        <!--<el-pagination class="page"
			      layout="total, prev, pager, next"
			      :page-size="goodsParam.pageSize"
			      :current-page="goodsParam.currPage"
		      	  @current-change="goodsPageIndexChange"
			      :total="goodsNum">
        </el-pagination>-->
      </div>
    </div>

    <div class="count">
      <div class="total_tip">
        <span v-if="clue.name=='续费'">续费</span>
        <span v-else>报名</span>结算
      </div>
      <div class="table">
        <div class="thead">
          <div style="width: 0.6rem;"></div>
          <div style="width: 1.8rem;">名称</div>
          <div style="width: 1.1rem;">总价</div>
          <div style="width: 1.25rem;">单价</div>
          <div style="width: 1.35rem;">购买数量</div>
          <div style="width: 0.7rem;">单位</div>
          <div style="width: 1.2rem;">合计金额</div>
          <div style="width: 1rem;">优惠</div>
          <div style="width: 1.1rem;">应收金额</div>
          <div style="width: 1rem;">操作</div>
        </div>
        <div class="tr_div" v-for="item,index in countList">
          <div class="tr">
            <div style="width: 0.6rem;">
              <span class="type">{{item.mode}}</span>
            </div>
            <div style="width: 1.8rem;" v-if="item.classId" class="tr_two_row">
              <div>{{item.name}}</div>
              <div>{{item.className?item.className : ''}}</div>
            </div>

            <div style="width: 1.8rem;" v-else>{{item.name}}</div>

            <div v-if="item.type=='商品'" style="width: 1.1rem;">￥{{item.price}}</div>
            <div v-else style="width: 1.1rem;" class="tr_two_row">
              <div>￥{{item.price}}</div>
              <div>共{{item.hour}}{{item.unit}}</div>
            </div>

            <div style="width: 1.25rem;">
              <template v-if="item.unitPrice">￥{{item.unitPrice}}/{{item.unit}}</template>
            </div>

            <div style="width: 1.35rem;">
              <div class="btn_reduce" v-if="item.buyNumMax" @click="reduceNum(item)">-</div>
              <div class="buy_num">{{item.buyNum}}</div>
              <div class="btn_add" v-if="item.buyNumMax" @click="addNum(item)">+</div>
            </div>
            <!--<div style="width: 0.9rem;">
							40
            </div>-->
            <div style="width: 0.7rem;">{{item.unit}}</div>
            <div style="width: 1.2rem;">￥{{item.sumPrice}}</div>
            <div style="width: 1rem;">￥{{item.discount}}</div>
            <div style="width: 1.1rem;">￥{{item.money}}</div>
            <div style="width: 1rem;">
              <div class="btn_del" @click="delCount(index)">删除</div>
            </div>
          </div>
        </div>

        <div class="compute">
          已选定 {{c_check_num}} 门课程&emsp;|&emsp;已选定 {{g_check_num}} 个商品
          <div class="compute_money">总计应收：￥{{totalMoney}}</div>
        </div>
      </div>
    </div>

    <div class="btn_div">
      <div class="btn_sure" @click="ok()">
        <span v-if="clue.name=='续费'">确定续费</span>
        <span v-else>确定报名</span>
      </div>
      <div class="btn_cancel" @click="cancel()">返 回</div>
    </div>
  </div>
</template>

<script>
var vm, dict;
export default {
  data: function() {
    return {
      checkTab: 1,
      //搜索关键词
      goodsParam: {
        name: "",
        campusId: "",
        goodsMode: "1,2,3",
        _wait: ""
      },
      courseParam: {
        courseName: "",
        studentId: "",
        campusId: "",
        _wait: ""
      },
      clue: {},
      //课程和商品总数
      courseNum: null,
      goodsNum: null,
      //课程,商品,结算列表
      courseList: [],
      goodsList: [],
      countList: [],
      //订单类型
      orderMode: null,
      //被勾选数组
      c_checkList: [],
      g_checkList: [],
      //数据字典
      courseModeMap: null,
      chargeModeMap: null,
      classModeMap: null,
      goodsMapMap: null,
      courseTimeMap: null
    };
  },
  computed: {
    c_check_num: function() {
      return this.c_checkList.length;
    },
    g_check_num: function() {
      return this.g_checkList.length;
    },
    totalMoney: function() {
      var money = 0;
      this.countList.forEach(function(count) {
        money += count.money;
      });
      return parseFloat(money.toFixed(2));
    }
  },
  methods: {
    init: function(clue) {
      vm.clue = clue;
      vm.checkTab = 1;

      //清空搜索参数
      vm.goodsParam = {
        name: "",
        campusId: clue.campusId,
        goodsMode: "1,2,3",
        _wait: ""
      };
      vm.courseParam = {
        courseName: "",
        studentId: clue.studentId,
        campusId: clue.campusId,
        _wait: ""
      };
      //清空总数
      vm.courseNum = null;
      vm.goodsNum = null;

      //清空数据列表
      vm.courseList = null;
      vm.goodsList = [];
      vm.countList = [];
      //清空选择列表
      vm.c_checkList = [];
      vm.g_checkList = [];

      //查询课程和商品列表
      vm.searchCourse();
      vm.searchGoods();
      //保存订金金额
      api.getMoney({ clueId: clue.clueId + "" }).then(function(data) {
        clue.earnestMoney = data.money;
      });
    },
    ok: function() {
      var counts = vm.countList;
      console.log(vm.countList);
      var type = null;
      let coursePackageIds = "";
      for (var i = 0; i < counts.length; i++) {
        if (counts[i].type != "商品") {
          if (type == null) {
            type = counts[i].type;
          }
          coursePackageIds +=
            coursePackageIds == "" ? counts[i].packId : "," + counts[i].packId;
        }
      }

      if (vm.countList.length == 0 || type == null) {
        tool.message({
          showClose: true,
          message: "请至少选择一项课程/班级",
          type: "warning"
        });
      } else {
        let param = {
          clueId: vm.clue.clueId + "",
          coursePackageIds: coursePackageIds
        };
        api.checkStudentCourse(param).then(function(data) {
          if (data.resultCode == 2000) {
            if (data.info.length != 0) {
              let showTitle = "";
              for (let n = 0; n < data.info.length; n++) {
                for (let i = 0; i < counts.length; i++) {
                  if (data.info[n].coursePackageId == counts[i].packId) {
                    showTitle +=
                      showTitle == "" ? counts[i].name : "、" + counts[i].name;
                  }
                }
              }
              vm.$confirm(
                "该学员已购买过" + showTitle + "课程，是否重新购买？",
                "是否重复购买课程",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  center: true,
                  type: "warning"
                }
              )
                .then(() => {
                  vm.$emit("ok", vm.countList);
                })
                .catch(() => {});
            } else {
              vm.$emit("ok", vm.countList);
            }
          } else {
            tool.message({
              showClose: true,
              message: data.message,
              type: "error"
            });
          }
        });
      }
    },
    cancel: function() {
      vm.$emit("cancel");
    },
    selectType: function(index) {
      vm.checkTab = index;
    },
    showSub: function(event) {
      var $icon = $(event.currentTarget);
      $icon.toggleClass("tr_icon_active");
      var $sub = $icon.parent().next();

      if ($sub.css("display") == "none") {
        $sub.slideDown();
      } else {
        $sub.slideUp();
      }
    },
    getUnit: function(course, pack) {
      //按时间收费
      if (course.chargeMode == 3) {
        return vm.courseTimeMap[pack.courseTimeMode];
      }
      //双师课
      if (course.courseType == 4) {
        return "节";
      }
      return "课时";
    },
    checkCourse: function(course, pack) {
      //别名
      var checks = vm.c_checkList;
      var counts = vm.countList;
      //获取当前类型,
      var type = course.classId ? "班级" : "课程";

      var id =
        course.classId + "-" + course.courseId + "-" + pack.coursePackageId;

      //判断是否被勾选
      var index = checks.indexOf(id);
      if (index > -1) {
        //已被勾选,从两个列表中删除
        for (var i = 0; i < counts.length; i++) {
          //counts[i].type==type &&
          if (counts[i].id == id) {
            counts.splice(i, 1);
            break;
          }
        }
        checks.splice(index, 1);
        return;
      }

      //未被勾选,被选的只能是课程或班级的一种
      //			for(var j=0; j<counts.length; j++) {
      //				if(counts[j].type!="商品" && counts[j].type!=type) {
      //					tool.message({ showClose: true, message: "只能选课程或班级中的一种", type: 'warning' });
      //					return;
      //				}
      //			}
      //创建结算对象
      var mode = vm.courseModeMap[course.courseMode];
      var count = {
        id: id,
        courseId: course.courseId,
        classId: course.classId,
        className: course.className,
        packId: pack.coursePackageId,
        type: type,
        name: course.courseName,
        unitPrice: "", //单价
        unit: vm.getUnit(course, pack), //单位
        price: pack.totalMoney, //总价
        hour: pack.courseHour, //课时
        buyNum: 1, //购买数量
        sumPrice: pack.totalMoney, //合计金额
        discount: 0, //优惠
        mode: course.classId ? mode : "课程"
      };

      if (course.chargeMode != 3) {
        //按课时和期时,计算单价
        count.unitPrice = Math.ceil((count.price * 100) / count.hour) / 100;
      }

      //计算购买数量
      if (course.classId) {
        //班级
        //按课时收费
        if (course.chargeMode == 1) {
          count.buyNum = course.totalHour - course.useCourseHour;
          count.buyNumMax = count.buyNum;
          //合计金额得根据剩余数量*单价计算
          count.sumPrice =
            Math.ceil(((count.price * 100) / count.hour) * count.buyNum) / 100;
        } else if (course.chargeMode == 2) {
          //按期或时间收费
          count.buyNum = course.totalHour;
        } else {
          count.buyNum = pack.courseHour;
        }
      } else {
        //课程
        //按课时收费
        if (course.chargeMode == 1) {
          count.buyNum = count.hour;
          count.buyNumMax = count.hour;
        } else {
          //按期或时间收费
          count.buyNum = count.hour;
        }
      }

      //计算应收金额
      var money = count.sumPrice - count.discount;
      money = money > 0 ? money : 0;
      count.money = parseFloat(money.toFixed(2));
      //加入列表
      counts.push(count);
      checks.push(id);
    },
    checkGoods: function(goods) {
      var id = goods.goodsId;
      //别名
      var checks = vm.g_checkList;
      var counts = vm.countList;
      //判断是否被勾选
      var index = checks.indexOf(id);
      if (index > -1) {
        //已被勾选,从两个列表中删除
        for (var i = 0; i < counts.length; i++) {
          if (counts[i].type == "商品" && counts[i].id == id) {
            counts.splice(i, 1);
            break;
          }
        }
        checks.splice(index, 1);
        return;
      }

      //未被勾选,但是没库存,直接结束
      if (goods.stockNum == 0) {
        return;
      }

      //未被勾选,创建结算对象
      var count = {
        id: id,
        type: "商品",
        name: goods.name,
        price: goods.salesPrice,
        unitPrice: goods.salesPrice,
        buyNum: 1,
        buyNumMax: goods.stockNum,
        sumPrice: goods.salesPrice,
        discount: 0,
        mode: "商品",
        unit: "件"
      };
      //计算应收金额
      var money = count.price - count.discount;
      money = money > 0 ? money : 0;
      count.money = parseFloat(money.toFixed(2));
      //加入列表
      counts.push(count);
      checks.push(id);
    },
    searchCourse: function() {
      api.courseClassList(vm.courseParam).then(function(data) {
        //遍历课程列表
        data.info.forEach(function(item) {
          var t = item.firstTime;
          //剪切拼接日期和时间
          item.firstDay = t ? t.substring(0, 10) : "";
          item.firstTime = t
            ? t.substring(11) + "-" + item.firstTimeEnd.substring(11)
            : "";
          //双师
          if (item.courseType == 4) {
            item.coursePackageEntityList.forEach(function(pack) {
              pack.courseHour = pack.syllabusNum;
            });
          }
          //按时间 - 天, 按期按课时 - 课时
          //					item.unitName = (item.chargeMode == 3? "天" : "课时");
        });
        vm.courseList = data.info;
      });
    },
    searchGoods: function() {
      api.goodsList(vm.goodsParam).then(function(data) {
        vm.goodsList = data.list;
      });
    },
    delCount: function(index) {
      //别名
      var counts = vm.countList;
      var checks =
        counts[index].type == "商品" ? vm.g_checkList : vm.c_checkList;

      var id = counts[index].id;
      //从两个列表删除数据
      checks.splice(checks.indexOf(id), 1);
      counts.splice(index, 1);
    },
    addNum: function(count) {
      if (count.buyNum == count.buyNumMax) {
        return;
      }
      //数量和总价钱
      count.buyNum++;

      //不是商品的不能按单价计算,因为单价本身有误差
      var sumPrice;
      if (count.type != "商品") {
        sumPrice =
          Math.ceil(((count.price * 100) / count.hour) * count.buyNum) / 100;
      } else {
        sumPrice = count.unitPrice * count.buyNum;
      }
      count.sumPrice = parseFloat(sumPrice.toFixed(2));

      //应收金额
      var money = count.sumPrice - count.discount;
      money = money > 0 ? money : 0;
      count.money = parseFloat(money.toFixed(2));
    },
    reduceNum: function(count) {
      if (count.buyNum <= 1) {
        return;
      }
      //数量和总价钱
      count.buyNum--;

      //不是商品的不能按单价计算,因为单价本身有误差
      var sumPrice;
      if (count.type != "商品") {
        sumPrice =
          Math.ceil(((count.price * 100) / count.hour) * count.buyNum) / 100;
      } else {
        sumPrice = count.unitPrice * count.buyNum;
      }
      count.sumPrice = parseFloat(sumPrice.toFixed(2));

      //应收金额
      var money = count.sumPrice - count.discount;
      money = money > 0 ? money : 0;
      count.money = parseFloat(money.toFixed(2));
    }
    //		goodsPageIndexChange : function(val) {
    //			vm.goodsParam.currPage = val;
    //	    	vm.searchGoods();
    //		}
  },
  created: function() {
    vm = this;
    dict = tool.getItem(lsKey.dict, true);
    vm.courseModeMap = tool.parseDict(dict["course_mode"]);
    vm.chargeModeMap = tool.parseDict(dict["charge_mode"]);
    vm.goodsModeMap = tool.parseDict(dict["goods_mode"]);
    vm.classModeMap = tool.parseDict(dict["class_status_mode"]);

    var m = tool.parseDict(dict["course_time_mode"]);
    //遍历单位,将不是年的,都加上"个"
    //		for(let k in m) {
    //			if(k != 1) {
    //				m[k] = "个"+m[k];
    //			}
    //		}
    vm.courseTimeMap = m;
  }
};
</script>
<style lang="scss">
#clue_enroll_choose {
  .el-input__inner {
    /*background-color: rgb(247,248,250);*/
  }
}
</style>
<style scoped src="../../../style/module/dialog.css"></style>
<style scoped src="../../../style/module/table2.css"></style>
<style scoped>
.btn_div {
  padding: 0.2rem 0;
}
/* ----------导航条---------- */
.nav_div {
  overflow: hidden;
  margin: 0 0.22rem;
  border-bottom: 0.01rem solid #f3f6fc;
}
.nav {
  width: 1.3rem;
  line-height: 0.35rem;
  float: left;
  color: #999999;
  font-size: 0.2rem;
  letter-spacing: 0.03rem;
  font-weight: bold;
  text-align: center;
  cursor: pointer;
}
.nav_active {
  color: #3885f8;
  border-bottom: 0.03rem solid #3885f8;
}

/* ----------课程---------- */
.content {
  padding: 0 0.3rem;
}
.condition {
  height: 0.38rem;
  margin-top: 0.1rem;
  margin-bottom: 0.05rem;
  /*outline: 1px solid red;*/
}
.tip {
  float: left;
  line-height: 0.38rem;
  color: #333333;
  font-size: 0.18rem;
  font-weight: bold;
}
.search {
  float: right;
  width: 3.5rem;
}

.tr_icon,
.sub_icon {
  float: left;
  width: 0.4rem;
  height: 0.3rem !important;
  margin-top: 0.11rem;
  /*outline: 0.01rem solid red;*/
  background-size: 0.18rem;
  background-repeat: no-repeat;
  background-position: 0.15rem center;
  cursor: pointer;
}
.sub_icon {
  margin-left: 0.2rem;
  background-image: url(../../../assets/img/clue_manage/check_no.png);
}
.sub_icon_active {
  background-image: url(../../../assets/img/clue_manage/check_yes.png);
}
.tr_icon {
  background-image: url(../../../assets/img/clue_manage/enroll_open.png);
}
.tr_icon_active {
  background-image: url(../../../assets/img/clue_manage/enroll_close.png);
}

.sub_time {
  float: right;
  width: 1.4rem;
}
.sub_money {
  float: right;
  width: 0.85rem;
}

.page {
  text-align: right;
  padding: 0.05rem 0.2rem;
}

/* ----------结算---------- */
.count {
  padding: 0 0.3rem;
}

.total_tip {
  line-height: 0.38rem;
  color: #333333;
  font-size: 0.18rem;
  font-weight: bold;
  margin: 0.15rem 0 0.05rem 0;
}
.type {
  margin-left: 0.1rem;
  display: inline-block;
  height: 0.2rem;
  line-height: 0.2rem;
  font-size: 0.12rem;
  background-color: #3885f8;
  color: white;
  border-radius: 0.05rem;
  padding: 0 0.05rem;
  margin-right: 0.03rem;
}

.tr_two_row {
  padding-top: 0.05rem;
  line-height: 0.2rem;
}
.btn_add,
.btn_reduce {
  display: inline-block;
  width: 0.25rem;
  height: 0.25rem;
  line-height: 0.25rem;
  margin-top: 0.11rem;
  /*float: left;*/
  /*outline: 1px solid red;*/
  font-size: 0.2rem;
  color: #3885f8;
  cursor: pointer;
  user-select: none;
}
.btn_reduce {
  /*margin-left: 0.3rem;*/
}
.buy_num {
  display: inline-block;
  min-width: 0.4rem;
  /*float: left;*/
  /*outline: 1px solid red;*/
  color: #3885f8;
}
.btn_del {
  /*outline: 1px solid red;*/
  width: 0.6rem;
  height: 0.25rem;
  line-height: 0.25rem;
  margin: 0.12rem auto 0 auto;
  text-align: left;
  padding-left: 0.22rem;
  color: #3885f8;
  background-image: url(../../../assets/img/clue_manage/enroll_del.png);
  background-size: 0.18rem;
  background-repeat: no-repeat;
  background-position: left center;
  cursor: pointer;
}
.compute {
  position: relative;
  line-height: 0.48rem;
  height: 0.48rem;
  text-align: center;
  background-color: rgb(248, 249, 253);
  color: #333333;
  font-size: 0.16rem;
}
.compute_money {
  position: absolute;
  width: 2rem;
  height: 0.48rem;
  right: 0.3rem;
  top: 0;
  text-align: right;
  font-weight: bold;
  color: #3885f8;
  /*outline: 1px solid blue;*/
}
</style>
